package cn.accjiyun.controller.admin;

import cn.accjiyun.core.controller.BaseController;
import cn.accjiyun.core.utils.MD5;
import cn.accjiyun.core.utils.SingletonLoginUtils;
import cn.accjiyun.model.system.SysUser;
import cn.accjiyun.service.SysUserService;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by jiyun on 2017/2/11.
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    private static String userPassPage = getViewPath("/admin/user/user-update");

    @Autowired
    private SysUserService sysUserService;

    @InitBinder({"sysUser"})
    public void initBinderSysUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("sysUser.");
    }

    /**
     * 修改用户密码
     *
     * @return Map<String,Object>
     */
    @RequestMapping("/updatePWD/{userId}")
    @ResponseBody
    public String updatePWD(HttpServletRequest request, @PathVariable("userId") int userId) {
        JsonObject resultJson = new JsonObject();
        try {
            String newPwd = request.getParameter("loginPwd");
            if (userId > 0 && newPwd != null && newPwd.trim().length() > 0) {
                SysUser sysuser = sysUserService.querySysUserByUserId(userId);
                sysuser.setLoginPwd(MD5.getMD5(newPwd));
                sysUserService.updateUserPwd(sysuser);

                resultJson.addProperty("status", 200);
                resultJson.addProperty("msg", "密码修改成功");
            }
        } catch (Exception e) {
            logger.error("UserController.updatePWD()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }


    /**
     * 初始化修改页面
     */
    @RequestMapping("/initUserUpdatePage")
    public ModelAndView initUserUpdatePage(HttpServletRequest request) {
        ModelAndView model = new ModelAndView();
        model.setViewName(userPassPage);
        SysUser sysUser = SingletonLoginUtils.getLoginSysUser(request);
        model.addObject("sysUser", sysUser);
        return model;
    }
}
